package com.ssm.subject.domain.handler.subejct;

import com.ssm.subject.common.enums.IsDeletedFlagEnum;
import com.ssm.subject.common.enums.SubjectInfoTypeEnum;
import com.ssm.subject.domain.bo.SubjectAnswerBO;
import com.ssm.subject.domain.bo.SubjectInfoBO;
import com.ssm.subject.domain.bo.SubjectOptionBO;
import com.ssm.subject.domain.convert.SubjectRadioConvert;
import com.ssm.subject.infra.basic.entity.SubjectRadio;
import com.ssm.subject.infra.basic.service.SubjectRadioService;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 单选策略类
 */
@Component
public class RadioTypeHandle implements SubejctTypeHandler {
    @Resource
    private SubjectRadioService subjectRadioService;
    @Override
    public SubjectInfoTypeEnum getHandlerType() {
        return SubjectInfoTypeEnum.RADIO;
    }

    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        //单选题目的插入
        List<SubjectRadio> subjectRadioList = new ArrayList<>(); //一个选项为一条数据，用List存
        List<SubjectAnswerBO> optionList = subjectInfoBO.getOptionList();
        //为空，直接返回,空集合使用foreach会空指针
        if(CollectionUtils.isEmpty(optionList)) {
            return;
        }
        optionList.forEach(subjectAnswerBO -> {
            SubjectRadio subjectRadio = SubjectRadioConvert.INSTANCE.subjectAnswerBoToRadio(subjectAnswerBO);
            subjectRadio.setSubjectId(subjectInfoBO.getId());
            subjectRadioList.add(subjectRadio);
        });
        subjectRadioService.batchInsert(subjectRadioList);
    }

    @Override
    public SubjectOptionBO query(Long subjetcId) {
        SubjectRadio subjectRadio = new SubjectRadio();
        subjectRadio.setSubjectId(subjetcId);
        subjectRadio.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectRadio> subjectRadioList = subjectRadioService.query(subjectRadio);
        List<SubjectAnswerBO> subjectAnswerBOS = SubjectRadioConvert.INSTANCE.subjectRadioListToAnswerBoList(subjectRadioList);
        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        subjectOptionBO.setOptionList(subjectAnswerBOS);
        return subjectOptionBO;
    }
}
